package com.ysxsoft.wdg.ui.activity.center_zy;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.classic.common.MultipleStatusView;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.order.ZyOrderDetailActivity;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.AddressBean;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.zy.GoodsBean;
import com.ysxsoft.wdg.bean.zy.ZyConfirmBean;
import com.ysxsoft.wdg.bean.zy.CreateIdBean;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.pay.PayListenerUtils;
import com.ysxsoft.wdg.pay.PayPopWindow;
import com.ysxsoft.wdg.pay.PayResultListener;
import com.ysxsoft.wdg.pay.PayUtils;
import com.ysxsoft.wdg.pay.WxPayBean;
import com.ysxsoft.wdg.ui.activity.address.AddressListActivity;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.util.statusbar.StatusBarUtil;
import com.ysxsoft.wdg.widget.alertview.AlertUtils;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class ZyGoodsConfirmActivity extends BaseActivity implements PayResultListener {


    public static void start(Context context, String product_rule_id, String num) {
        Intent intent = new Intent(context, ZyGoodsConfirmActivity.class);
        intent.putExtra("product_rule_id", product_rule_id);
        intent.putExtra("num", num);
        context.startActivity(intent);
    }

    private View mRootView;

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.tv_address_phone)
    TextView tvAddressPhone;
    @BindView(R.id.tv_address_address)
    TextView tvAddressAddress;
    @BindView(R.id.iv_goods)
    ImageView ivGoods;
    @BindView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_rules)
    TextView tvRules;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_yun)
    TextView tvYun;
    @BindView(R.id.tv_total_num)
    TextView tvTotalNum;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.rl_add_address)
    RelativeLayout rlAddAddress;
    @BindView(R.id.ll_address_has)
    LinearLayout llAddressHas;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private GoodsBean goodsBean;
    private String orderId = "", product_rule_id = "", uid = "", num = "", addressId = "", payMoney = "", yuE = "";


    private PayPopWindow payPopWindow;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_goods_order_confirm;
    }

    @Override
    protected void initData() {
        StatusBarUtil.setTranslucentStatus(this, true);
        initStatusBar(topView, false);
        titleContent.setText("确认订单");

        mRootView = View.inflate(this, R.layout.activity_goods_order_confirm, null);

        uid = SharePrefUtils.getUserId();

        Intent intent = getIntent();
        product_rule_id = intent.getStringExtra("product_rule_id");
        num = intent.getStringExtra("num");

        multStatusView.showLoading();
        mApiHelper.sureZyOrder(uid, product_rule_id, num, new Observer<BaseBean<ZyConfirmBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<ZyConfirmBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    ZyConfirmBean confirmBean = baseBean.getData();
                    AddressBean addressBean = confirmBean.getAddress();
                    goodsBean = confirmBean.getGoods();

                    if (addressBean != null) {
                        llAddressHas.setVisibility(View.VISIBLE);
                        rlAddAddress.setVisibility(View.GONE);
                        tvAddressName.setText(addressBean.getName());
                        tvAddressPhone.setText(addressBean.getPhone());
                        tvAddressAddress.setText(addressBean.getProvince() + addressBean.getCity() + addressBean.getCounty() + addressBean.getAddress());
                        addressId = addressBean.getId();
                    } else {
                        llAddressHas.setVisibility(View.GONE);
                        rlAddAddress.setVisibility(View.VISIBLE);
                    }

                    Glide.with(mContext).load(goodsBean.getPic()).into(ivGoods);
                    tvGoodsName.setText(goodsBean.getName());
                    tvMoney.setText(getString(R.string.price_rmb, goodsBean.getL_price()));
                    tvRules.setText(goodsBean.getRule_name());

                    tvYun.setText(getString(R.string.price_rmb, goodsBean.getYun()));
                    tvTotalNum.setText("共" + num + "件商品  合计");
                    payMoney = goodsBean.getTotal();
                    tvTotalMoney.setText(getString(R.string.price_rmb, payMoney));

                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                multStatusView.showContent();
            }
        });
    }

    @OnClick({R.id.title_finish, R.id.ll_address, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.ll_address:
                toAddressListActivity();
                break;
            case R.id.btn_commit:
                if (TextUtils.isEmpty(addressId)) {
                    ToastUtils.showToast("请选择收货地址");
                    return;
                }

                if (TextUtils.isEmpty(orderId) || TextUtils.isEmpty(yuE)) {
                    createOrder();
                } else {
                    showPayWindow();
                }
                break;
        }
    }

    private void createOrder() {
        mApiHelper.orderAdd(uid, addressId, payMoney, product_rule_id, num + "",
                new Observer<BaseBean<CreateIdBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseBean<CreateIdBean> baseBean) {
                        if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                            CreateIdBean idBean = baseBean.getData();
                            orderId = idBean.getOrderid();
                            yuE = idBean.getYu();
                            showPayWindow();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void showPayWindow() {

        if (payPopWindow != null) {
            payPopWindow.dismiss();
            payPopWindow = null;
        }

        payPopWindow = new PayPopWindow(this, payMoney, yuE);
        payPopWindow.show(mRootView);

        payPopWindow.setOnPayLiatener(new PayPopWindow.OnPayLiatener() {
            @Override
            public void payType(int payType) {//payment= "3";//支付方式 1=>微信 2=>支付宝 3=>账户余额 4=>积分支付
                AlertUtils.payAlert(ZyGoodsConfirmActivity.this);
                switch (payType) {
                    case 0://余额支付
                        postPayYue();
                        break;
                    case 1://支付宝支付
                        postPayZfb();
                        break;
                    case 2://微信支付
                        postPayWx();
                        break;
                }
            }
        });
    }

    /**
     * 自营商品微信支付
     */
    private void postPayWx() {
        mApiHelper.payZyWx(uid, orderId, payMoney, "0", new Observer<BaseBean<WxPayBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<WxPayBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    PayUtils.getInstance(mContext).toWxPay(baseBean.getData());
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void postPayZfb() {
        mApiHelper.payZyZfb(uid, orderId, payMoney, "0", new Observer<BaseBean<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<String> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    PayUtils.getInstance(mContext).pay(ZyGoodsConfirmActivity.this,
                            PayUtils.PAY_TYPE_ALI, baseBean.getData(), null);
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void postPayYue() {//type  	是否积分抵现，0否1是
        mApiHelper.payZyYue(uid, orderId, payMoney, "0", new Observer<BaseBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    PayListenerUtils.getInstance(mContext).addSuccess();
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    protected void setListener() {
        PayListenerUtils.getInstance(this).addListener(this);
    }


    private void toOrderDetail() {

        AlertUtils.dismissAlert();
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ZyOrderDetailActivity.start(mContext, orderId, true);
            }
        });
        finish();
    }

    @Override
    public void onPaySuccess() {
        ToastUtils.showToast("支付成功");
        toOrderDetail();
    }

    @Override
    public void onPayError() {
        ToastUtils.showToast("支付失败");
        toOrderDetail();
    }

    @Override
    public void onPayCancel() {
        ToastUtils.showToast("取消支付");
        toOrderDetail();
    }

    //选择地址
    private void toAddressListActivity() {
        Intent intent = new Intent(this, AddressListActivity.class);
        intent.putExtra("code", 1);
        startActivityForResult(intent, AddressListActivity.ADDRESS_CHOOSE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AddressListActivity.ADDRESS_CHOOSE) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    llAddressHas.setVisibility(View.VISIBLE);
                    rlAddAddress.setVisibility(View.GONE);
                    AddressBean item = data.getParcelableExtra("address");
                    addressId = item.getId() + "";
                    tvAddressAddress.setText(item.getAddress());
                    tvAddressName.setText(item.getName());
                    tvAddressPhone.setText(item.getPhone());
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        PayListenerUtils.getInstance(mContext).removeListener(this);
        super.onDestroy();
    }

}
